package org.example;

import java.nio.file.Path;
import java.time.Duration;
import java.util.Optional;

public class Options {

    /** sampling interval */
    private Duration interval = Duration.ofMillis(10);

    /** where to store flame graph */
    private Optional<Path> flamePath;

    /** whether print method table */
    private boolean printMethodTable = true;

    public Options(String agentArgs) {
        // parse arguments
        initOptions(agentArgs);
    }

    private void initOptions(String agentArgs) {
        if (agentArgs == null || agentArgs.isEmpty()) {
            return;
        }
        String[] split = agentArgs.split(",");
        for (String pair : split) {
            String[] kv = pair.split("=");
            if (kv.length != 2) {
                onError("Invalid argument: " + pair);
            }
            String key = kv[0];
            String value = kv[1];
            switch (key) {
                case "help" -> printHelp();
                case "interval" -> interval = Duration.ofNanos((long) Double.parseDouble(value) * 1000000);
                case "flamegraph" -> flamePath = Optional.of(Path.of(value));
                case "table" -> printMethodTable = Boolean.parseBoolean(value);
                default -> onError("Invalid key: " + key);
            }
        }
    }

    private void printHelp() {
        System.out.println("""
                Usage: java -javaagent:tiny-profiler.jar=options ...
                Options:
                    help: Print this help message
                    interval: The interval in milliseconds between samples (default: 10)
                    flamegraph: The path to the output file (default: no output)
                    table: Print the method table? (default: true)
                """);
    }

    private void onError(String msg) {
        System.err.println(msg);
        printHelp();
        System.exit(1);
    }

    public Duration getInterval() {
        return interval;
    }

    public Optional<Path> getFlamePath() {
        return flamePath;
    }

    public boolean isPrintMethodTable() {
        return printMethodTable;
    }
}
